const marked = require('marked')
const path = require('path')
const fs = require('fs')
const glob = require('glob')

marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: true,
  smartLists: true,
  smartypants: false
})

function publish(file, layout, done) {
  let html_dir = path.dirname(file).replace('markdown', 'html')
  let html_name = path.basename(file, '.md') + '.html'
  let html_file = path.format({
    dir: html_dir,
    base: html_name
  })
  fs.readFile(file, (err, file) => {
    if (err) return done(err)
    let mk_content = file.toString()
    let content = marked(mk_content)
    let html = layout.toString().replace('{{markdown-body}}', content)
    if (fs.existsSync(html_dir)) {
      fs.writeFile(html_file, html, (err) => {
        if (err) return done(err)
        return done(null, html_file)
      })
    } else {
      fs.mkdir(html_dir, err => {
        if (err) return done(err)
        fs.writeFile(html_file, html, (err) => {
          if (err) return done(err)
          return done(null, html_file)
        })
      })
    }
  })
}

const mk_path = path.join('markdown/**/*.md')

let files = glob.sync(mk_path)

let html_array = []
files.forEach((item, index, files) => {
  fs.readFile('layout/pages.html', 'utf-8', (err, layout) => {
    if (err) throw err
    publish(item, layout,(err, html_file) => {
      if (err) throw err
      console.log(`The file ${html_file} published！`)
    })
  })
  html_array.push(item.replace('markdown', 'html').replace('.md', '.html'))
})

fs.writeFile('html.json', JSON.stringify(html_array), err => {
  if (err) throw err
  console.log('写入完毕')
})
